﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using OnlineRailway.Administrator;
using OnlineRailway.EF;

namespace OnlineRailway.Administrator
{
    public partial class AccountManagement : System.Web.UI.Page
    {
        private SqlCommand cmd;
        private SqlConnection conn = Connect.Conn;
        private SqlDataAdapter dataAdapter;
        private DataSet ds = new DataSet();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindAccount();
            }
            lblMessage.Text = "";
        }
        void BindAccount()
        {
            
            #region ADO.NET
            try
            {
                cmd = new SqlCommand("SELECT [AccountID],[UserName],[FullName],[Age]=convert(varchar, Age, 110),[Gender],[Address],[Telephone],[Email],[Images],[Qualification],[Role] FROM Accounts", conn);
                if (conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }
                dataAdapter = new SqlDataAdapter(cmd);
                dataAdapter.Fill(ds);
                
                if (ds.Tables[0].Rows.Count > 0)
                {
                    gvAccount.DataSource = ds;
                    gvAccount.DataBind();
                }
                else
                {
                    ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
                    gvAccount.DataSource = ds;
                    gvAccount.DataBind();
                    int columncount = gvAccount.Rows[0].Cells.Count;
                    gvAccount.Rows[0].Cells.Clear();
                    gvAccount.Rows[0].Cells.Add(new TableCell());
                    gvAccount.Rows[0].Cells[0].ColumnSpan = columncount;
                    gvAccount.Rows[0].Cells[0].Text = "No Records Found";
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Error Bind: " + ex.Message;
            }
            finally { conn.Close(); }
            #endregion

            #region EF
            /*using (var context = new RailwayOnlineEntities())
            {
                try
                {
                    if (context.Accounts.Any())
                    {
                        gvAccount.DataSource = context.Accounts;
                        gvAccount.DataBind();
                    }
                    else
                    {
                        var obj = new List<Customer>();
                       obj.Add(new Customer());
                       // Bind the DataTable which contain a blank row to the GridView
                       gridSample.DataSource = obj;
                       gridSample.DataBind();
                       int columnsCount = gridSample.Columns.Count;
                       gridSample.Rows[0].Cells.Clear();// clear all the cells in the row
                       gridSample.Rows[0].Cells.Add(new TableCell()); //add a new blank cell
                       gridSample.Rows[0].Cells[0].ColumnSpan = columnsCount; //set the column span to the new added cell
 
                       //You can set the styles here
                       gridSample.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
                       gridSample.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Red;
                       gridSample.Rows[0].Cells[0].Font.Bold = true;
                       //set No Results found to the new added cell
                       gridSample.Rows[0].Cells[0].Text = "NO RESULT FOUND!";
                    }
                }
                catch (Exception ex)
                {

                    lblMessage.Text = ex.Message;
                }

            }*/
            #endregion
        }

        
        protected enum Roles2
        {
            Admin=0,
            Staff=1,
            Customer=2
        }
        

        protected void gvAccount_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvAccount.EditIndex = e.NewEditIndex;
            BindAccount();
        }

        protected void gvAccount_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvAccount.EditIndex = -1;
            BindAccount();
        }


        protected void gvAccount_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //var AccID = gvAccount.Rows[e.RowIndex].FindControl["name"] as Control;
            //var AccID = gvAccout.Rows[e.RowIndex].Cells[0].Controls[1] //Ngoai giao dien khong co control
            var AccID = Convert.ToInt32(gvAccount.DataKeys[e.RowIndex]["AccountID"]);
            var username = gvAccount.DataKeys[e.RowIndex].Values["UserName"].ToString();
            using (var context = new RailwayOnlineEntities())
            {
                var obj = context.Accounts.First(x => x.AccountID == AccID);
                var d =obj.Images;
                context.Accounts.DeleteObject(obj);
                context.SaveChanges();
                if (d != "")
                {
                    System.IO.File.Delete(Server.MapPath(d));
                }
                lblMessage.Text = "Account " + username + " has been deleted!";

            }

            BindAccount();
        }

        protected void gvAccount_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                var row = gvAccount.Rows[e.RowIndex];
                var age = Convert.ToDateTime("10/10/1990");
                try
                {
                    age = Convert.ToDateTime(((TextBox)row.FindControl("txtAgeEdit")).Text);
                }
                catch (Exception ex)
                {
                    lblMessage.Text = "• Your enter age isn't match format(MM/dd/yyyy)!";
                    return;
                }
                var accID = Convert.ToInt32(gvAccount.DataKeys[e.RowIndex]["AccountID"]);
                var username = gvAccount.DataKeys[e.RowIndex].Values["UserName"].ToString();
                var fullname = ((TextBox)row.FindControl("txtFullNameEdit")).Text;
                var gender = ((DropDownList)gvAccount.Rows[e.RowIndex].FindControl("ddlGenderEdit")).Text;
                var address = ((TextBox)row.FindControl("txtAddressEdit")).Text;
                var telephone = ((TextBox)row.FindControl("txtTelephoneEdit")).Text;
                var email = ((TextBox)row.FindControl("txtEmailEdit")).Text;

                var fileUpload = ((FileUpload)row.FindControl("fuImageEdit"));
                
                String imgPath = "~/StorageImage/AccountImages/"+fileUpload.FileName;
                

                var qualification = ((TextBox)row.FindControl("txtQualificationEdit")).Text;
                int role = 0;
                switch (((DropDownList)row.FindControl("ddlRoleEdit")).Text)
                {
                    case "Admin":
                        role = 0;
                        break;
                    case "Staff":
                        role = 1;
                        break;
                    default:
                        role = 2;
                        break;
                }
               
                if (fullname != null && age != null && gender != null && address != null && role != null && accID != null)
                {
                    using (var context = new RailwayOnlineEntities())
                    {
                        var obj = context.Accounts.First(x => x.AccountID == accID);
                        if (obj!=null)
                        {
                            obj.FullName = fullname;
                            obj.Age = age;
                            obj.Gender = gender;
                            obj.Address = address;
                            obj.Telephone = telephone;
                            obj.Email = email;
                            if (fileUpload.PostedFile != null && fileUpload.PostedFile.FileName != "")
                            {
                                if (fileUpload.PostedFile.ContentLength > 1048576)
                                {
                                    
                                    Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big! File must be less than 1MB.')", true);
                                }
                                else
                                {
                                    obj.Images = imgPath;
                                    fileUpload.SaveAs(Server.MapPath(imgPath));
                                }
                            }
                            obj.Qualification = qualification;
                            obj.Role = role;
                            context.SaveChanges();
                            lblMessage.Text = "Account " + username + " has been updated!";
                        }
                    }
                    gvAccount.EditIndex = -1;
                    
                }
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Error Update: " + ex.Message;
                
            }
            finally {  }
            BindAccount();

        }

        protected void gvAccount_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string username = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "UserName"));
                var lnkbtnresult = (ImageButton)e.Row.FindControl("ibtnDelete");
                if (lnkbtnresult != null)
                {
                    lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + username + "')");
                }

            }
        }

        
    }
}